/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/*
 * OrderEntryPanel.java
 *
 * Created on 11-Jan-2011, 6:51:26 PM
 */
package com.bullionxpress.client.view;

import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.bullionxpress.shared.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JDialog;
import com.bullionxpress.client.application.ClientGlobals;
import com.bullionxpress.shared.model.Instrument;
import com.bullionxpress.shared.model.LimitOrder;
import com.bullionxpress.shared.model.MarketOrder;
import com.bullionxpress.shared.service.MarketService;
import com.bullionxpress.shared.model.Order;
import com.bullionxpress.shared.model.OrderType;
import com.bullionxpress.shared.service.InstrumentDatabase;
import com.bullionxpress.shared.util.Utility;
import javax.swing.JOptionPane;

/**
 *
 * @author BullionXpress.com
 */
public class OrderEntryPanel extends javax.swing.JPanel {

    JDialog parent = null;

    /** Creates new form OrderEntryPanel */
    public OrderEntryPanel(JDialog parent) {
        try {
            this.parent = parent;
            initComponents();
            ////
            instrumentDropDownBox.removeAllItems();
            InstrumentDatabase db = ClientGlobals.instrumentDatabase;
            db.connect();

            Instrument[] ins = db.getAll();
            if (ins != null) {
                for (int i = 0; i < ins.length; i++) {
                    instrumentDropDownBox.addItem(ins[i].getSymbol());
                }
            }
        } catch (RemoteException ex) {
            Log.info(ex);
        }

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        executeButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        buyRadioButton = new javax.swing.JRadioButton();
        sellRadioButton = new javax.swing.JRadioButton();
        instrumentDropDownBox = new javax.swing.JComboBox();
        instrumentLabel = new javax.swing.JLabel();
        quantityLabel = new javax.swing.JLabel();
        quantityField = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        marketOrderRadioButton = new javax.swing.JRadioButton();
        limitPriceLabel = new javax.swing.JLabel();
        limitPriceField = new javax.swing.JTextField();
        expiryDateLabel = new javax.swing.JLabel();
        expiryDateField = new javax.swing.JTextField();
        limitOrderRadioButton = new javax.swing.JRadioButton();

        executeButton.setText("Execute");
        executeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                executeButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Order Entry"));

        buttonGroup1.add(buyRadioButton);
        buyRadioButton.setSelected(true);
        buyRadioButton.setText("Buy");

        buttonGroup1.add(sellRadioButton);
        sellRadioButton.setText("Sell");

        instrumentDropDownBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        instrumentLabel.setText("Instrument");

        quantityLabel.setText("Quantity");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(instrumentDropDownBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(instrumentLabel)
                    .addComponent(buyRadioButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(sellRadioButton)
                    .addComponent(quantityField, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quantityLabel))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(sellRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(quantityLabel)
                                .addGap(28, 28, 28))
                            .addComponent(quantityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(buyRadioButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(instrumentLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(instrumentDropDownBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Order Type"));

        buttonGroup2.add(marketOrderRadioButton);
        marketOrderRadioButton.setSelected(true);
        marketOrderRadioButton.setText("Market Order");
        marketOrderRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                marketOrderRadioButtonActionPerformed(evt);
            }
        });

        limitPriceLabel.setText("Limit Price");

        limitPriceField.setEnabled(false);

        expiryDateLabel.setText("Expiry [dd-mm-yyyy]");

        buttonGroup2.add(limitOrderRadioButton);
        limitOrderRadioButton.setText("Limit Order");
        limitOrderRadioButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                limitOrderRadioButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(marketOrderRadioButton)
                    .addComponent(limitOrderRadioButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(limitPriceLabel)
                    .addComponent(expiryDateLabel)
                    .addComponent(expiryDateField)
                    .addComponent(limitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(limitPriceLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(marketOrderRadioButton)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(limitOrderRadioButton))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(limitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(expiryDateLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(expiryDateField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cancelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 102, Short.MAX_VALUE)
                        .addComponent(executeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(executeButton))
                .addContainerGap(19, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
        parent.dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void executeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_executeButtonActionPerformed
        // TODO add your handling code here:
        Log.info("Execute Order");
        try {
            /////////////////////////////////
            // HACK
            if( ClientGlobals.account.getBalance() == 0 ){
                JOptionPane.showMessageDialog(null, "Insufficient Funding.");
                return;
            }
            // HACK
            /////////////////////////////////

            if( !Utility.isValidQuantity(quantityField.getText()) ){
                JOptionPane.showMessageDialog(parent, "Invalid quantity, positive numbers only.");
                return;
            }

            if( !Utility.isValidExpiry(expiryDateField.getText())){
                JOptionPane.showMessageDialog(parent, "Expiry format is: dd-mm-yyyy.");
                return;
            }

            MarketService service = ClientGlobals.marketService;
            Order o = null;
            if (marketOrderRadioButton.isSelected()) {
                o = new MarketOrder();
            } else {
                o = new LimitOrder();
                if( !Utility.isValidLimitPrice(limitPriceField.getText())){
                    JOptionPane.showMessageDialog(parent, "Invalid limit price, postive number values only.");
                    return;
                }
                String v = limitPriceField.getText();
                double price = 0;
                try {
                    price = Double.parseDouble(v);
                } catch (Exception ex) {
                    Log.info(ex);
                }
                o.setPrice(price);
            }

            o.setAccount(ClientGlobals.account);
            o.setInstrument(new Instrument((String)instrumentDropDownBox.getSelectedItem()));

            if (sellRadioButton.isSelected()) {
                o.setOrderType(OrderType.SELL);
            } else if (buyRadioButton.isSelected()) {
                o.setOrderType(OrderType.BUY);
            }

            String q = quantityField.getText();
            int units = Integer.parseInt(q);
            o.setUnits(units);

            String ed = expiryDateField.getText();
            if (ed == null || ed.equals("")) {
                Calendar c = Calendar.getInstance();
                c.add(Calendar.YEAR, 1);
                Date exp = c.getTime();
                o.setExpiry(exp);
            } else {
                SimpleDateFormat fmt = new SimpleDateFormat("dd-mm-yyyy");
                try {
                    o.setExpiry(fmt.parse(ed));
                } catch (Exception ex) {
                    Log.info(ex);
                }
            }
            
            try {
                Log.info("service.offer(o):");
                service.offer(o);
                Log.info("Order executed");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, ex.toString());
                Log.info(ex);
            }

            parent.dispose();

        } catch (Exception ex) {
            Log.info(ex);
        }
    }//GEN-LAST:event_executeButtonActionPerformed

    private void marketOrderRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_marketOrderRadioButtonActionPerformed
        // TODO add your handling code here:
        limitPriceField.setEnabled(false);
    }//GEN-LAST:event_marketOrderRadioButtonActionPerformed

    private void limitOrderRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limitOrderRadioButtonActionPerformed
        // TODO add your handling code here:
        limitPriceField.setEnabled(true);
    }//GEN-LAST:event_limitOrderRadioButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JRadioButton buyRadioButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton executeButton;
    private javax.swing.JTextField expiryDateField;
    private javax.swing.JLabel expiryDateLabel;
    private javax.swing.JComboBox instrumentDropDownBox;
    private javax.swing.JLabel instrumentLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JRadioButton limitOrderRadioButton;
    private javax.swing.JTextField limitPriceField;
    private javax.swing.JLabel limitPriceLabel;
    private javax.swing.JRadioButton marketOrderRadioButton;
    private javax.swing.JTextField quantityField;
    private javax.swing.JLabel quantityLabel;
    private javax.swing.JRadioButton sellRadioButton;
    // End of variables declaration//GEN-END:variables
}
